<?php
/**
 * Created by PhpStorm.
 * User: cgp
 * Date: 14-2-14
 * Time: 下午3:14
 */
use pft\Log\Log;

//include '/var/www/html/new/d/common/autoload.php';
include '/var/www/html/new/d/class/Log.class.php';
require("/var/www/html/new/conf/le.je");
require_once("/var/www/html/new/d/alipay/ali_order/func.inc.php");//total_fee fenRun write_logs
$le=new go_sql();
$le->connect();
define('LOG_PATH', '/var/www/html/new/d/module/zax/ips_pay/log/log.txt');
//----------------------------------------------------
//  接收数据
//  Receive the data
//----------------------------------------------------

//$_GET = json_decode('{"billno":"1856210","mercode":"026188","amount":"0.06","date":"20150812","succ":"Y","msg":null,"ipsbillno":"NT20150812199594","retencodetype":"17","attach":"支付订单1856210","Currency_type":"RMB","signature":"d6399a31e116f4ec4e4d0695b3dabd82","ipsbanktime":"20150812163603","bankbillno":"310000830032"}',true);


$ordern = $_GET['billno'];
$amount = $_GET['amount'];
$mydate = $_GET['date'];
$succ = $_GET['succ'];
$msg = $_GET['msg'];
$attach = $_GET['attach'];
$ipsbillno = $_GET['ipsbillno'];
$retEncodeType = $_GET['retencodetype'];
$currency_type = $_GET['Currency_type'];
$signature = $_GET['signature'];
//'----------------------------------------------------
//'   Md5摘要认证
//'   verify  md5
//'----------------------------------------------------

//RetEncodeType设置为17（MD5摘要数字签名方式）
//交易返回接口MD5摘要认证的明文信息如下：
//billno+【订单编号】+currencytype+【币种】+amount+【订单金额】+date+【订单日期】+succ+【成功标志】+ipsbillno+【IPS订单编号】+retencodetype +【交易返回签名方式】+【商户内部证书】
//例:(billno000001000123currencytypeRMBamount13.45date20031205succYipsbillnoNT2012082781196443retencodetype17GDgLwwdK270Qj1w4xho8lyTpRQZV9Jm5x4NwWOTThUa4fMhEBK9jOXFrKRT6xhlJuU2FEa89ov0ryyjfJuuPkcGzO5CeVx5ZIrkkt1aBlZV36ySvHOMcNv8rncRiy3DQ)

//返回参数的次序为：
//billno + mercode + amount + date + succ + msg + ipsbillno + Currecny_type + retencodetype + attach + signature + bankbillno
//注2：当RetEncodeType=17时，摘要内容已全转成小写字符，请在验证的时将您生成的Md5摘要先转成小写后再做比较
$content = 'billno'.$ordern.'currencytype'.$currency_type.'amount'.$amount.
    'date'.$mydate.'succ'.$succ.'ipsbillno'.$ipsbillno.'retencodetype'.$retEncodeType;
//请在该字段中放置商户登陆merchant.ips.com.cn下载的证书
//$cert = '76676591919293971034703297888078624026275659246382804796238960393156885586815305050516493889730425518949732797083380078766300585';
$cert = '6868423594683207055317415846359181319229560680572746757844258714459288782574783'.
    '5274502434575961846130383064183151730364216831296';
$signature_1ocal = md5($content . $cert);

$word = date('Y-m-d H:i:s').'记录开始:|' . json_encode($_GET);
Log::writeLog($word, LOG_PATH);

if ($signature_1ocal == $signature)
{
    //----------------------------------------------------
    //  判断交易是否成功
    //  See the successful flag of this transaction
    //----------------------------------------------------
    if ($succ == 'Y')
    {
        $s = new SoapClient(null,array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
        );
        $sourceT = 3;//环迅
        $str="select status,total_fee from pft_alipay_rec where out_trade_no='$ordern' AND `sourceT`=$sourceT LIMIT 1";
        $GLOBALS['le']->query($str);
        $ipsRes = $GLOBALS['le']->fetch_assoc();
        $royalty_parameters = $ipsRes['royalty_parameters'];
        $total_fee = $ipsRes['total_fee'];
        if($ipsRes['status']==0) {
            if($amount!=$ipsRes['total_fee']){
                $word = '支付金额不等。返回金额:' . $amount . ',实际金额:'. $total_fee;
                Log::writeLog($word,LOG_PATH);
                @$GLOBALS['le']->close();
                exit('交易失败');
            }

            //更新记录状态为已支付
            $str="update pft_alipay_rec set status=1,dtime=now(),trade_no='$ipsbillno' where out_trade_no='$ordern' AND sourceT=$sourceT  limit 1";
            $GLOBALS['le']->query($str);

            require("/var/www/html/new/d/class/OrderRecord.php");

            $or=new OrderRecord($ordern,$s);

            $orders=$or->info();
            $mainOrder=$orders['mainOrder'];
            $mid=(string)$mainOrder->UUmid;
            $aid=(string)$mainOrder->UUaid;

            if((string)$orders['mainOrder']->UUpaystatus==1) {
                $word = '订单已支付';
                Log::writeLog($word, LOG_PATH);
            }
            //给总帐号加钱
            $alipay_to_pft = true;
            $total_fee = total_fee($orders,1);// 获取总价格
            $p_type = 6;//环迅支付
            if($aid!=$mid) {
                // 非自身供应须分润  返回值是上级的利润
                $aid_money = fenRun($s, $ordern, $aid, $mid, $total_fee, $orders, $alipay_to_pft,$p_type);
            } else{// 支付给票付通需给自供自销的分销商加上相应金额
                if($alipay_to_pft){
                    $s->PFT_Member_Fund_Modify($mid, 0, $total_fee, 0, 0,null,0, 1,$ordern,$p_type);
                }
            }

            //更新远端订单号,环迅支付
            $s->Remote_Ordernum_Update(serialize(array($ordern=>'PC_IPS_PFT_'.$_SERVER['REQUEST_TIME'])));
            /*只更新订单支付状态*/
            $s->Mod_Order_Status($ordern,1,8);//1表示paystatus改成1 已支付   8表示 pmode改成8 环迅支付

            //演出订单更新座位状态
//            if((string)$orders['mainOrder']->UUp_type=='H')
//            {
//                $relation_info_req = http_build_query(array(
//                    'Action'  => 'Relation_after_pay',
//                    'Ordern'  => $ordern,
//                    'Fid'     => (int)$orders['mainOrder']->UUmid,
//                ));
//                file_get_contents('http://10.160.4.140/new/d/api/Product_check_h.php?'.$relation_info_req);
//            }
            // 支付后交互
            $tid = (int)$orders['mainOrder']->UUtid;
            $sql = "select Mpath,Mdetails from uu_jq_ticket where id=$tid limit 1";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            if(($Mpath=$GLOBALS['le']->f('Mpath'))){

                $relation_info_req = http_build_query(array(
                    'Action'  => 'Relation_after_pay',
                    'Ordern'  => $ordern,
                    'Fid'     => (int)$orders['mainOrder']->UUmid,
                ));
                file_get_contents($Mpath.'?'.$relation_info_req);
            }
            //最后重发短信
            include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual  = new \PFT\SMS\OrderSmsManual($s);
            $ret = $smsManual->SendByOrderInfo($orders,true,false);//通知供应商 不发送微信通知
        }else{
            $word = date('Y-m-d H:i:s').'状态已完成';
            Log::writeLog($word, LOG_PATH);
            echo 'ipscheckok';
            @$GLOBALS['le']->close();
            exit;
        }
        $word = date('Y-m-d H:i:s').'交易成功！后台处理完毕|';
        Log::writeLog($word, LOG_PATH);
        echo 'ipscheckok';
        @$GLOBALS['le']->close();
    }else{
        $word = date('Y-m-d H:i:s').'Succ不为"Y"|';
        Log::writeLog($word, LOG_PATH);
        echo '交易失败！';
        exit;
    }
}else{
    $word = date('Y-m-d H:i:s') . '签名不正确!';
    Log::writeLog($word,LOG_PATH);
    echo '签名不正确！';
    exit;
}



?>